package com.baidu.health.service;

import com.baidu.health.mapper.TbArticleMapper;
import com.baidu.health.pojo.TbArticle;
import com.baidu.health.pojo.resultVo.articleVo;
import com.baidu.health.pojo.resultVo.resCollectList;
import com.baidu.health.pojo.resultVo.resultVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baidu.health.pojo.TbCollect;
import com.baidu.health.mapper.TbCollectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TbCollectServiceImpl extends ServiceImpl<TbCollectMapper, TbCollect>{

    @Autowired
    TbCollectMapper collectMapper;

    @Autowired
    TbArticleMapper articleMapper;

    public resultVo collectArticle(TbCollect collect) {

        TbArticle article = articleMapper.selectOne(new QueryWrapper<TbArticle>().lambda().eq(TbArticle::getArticleId, collect.getArticleId()));

        QueryWrapper<TbCollect> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(TbCollect::getUserId,collect.getUserId());
        wrapper.lambda().eq(TbCollect::getArticleId,collect.getArticleId());

        TbCollect tbCollect = collectMapper.selectOne(wrapper);

        if ( tbCollect == null ){
            collectMapper.insert(collect);
            article.setArticleCollectNums(article.getArticleCollectNums() + 1);
            articleMapper.updateById(article);
            return new resultVo(200,"收藏成功",null);
        }else {
//            if ( tbCollect.getDelFlag() == 0 ){
                collectMapper.deleteById(tbCollect.getCollectId());
                tbCollect.setUpdateTime(new Date());
                collectMapper.updateById(tbCollect);
                article.setArticleCollectNums(article.getArticleCollectNums() - 1);
                articleMapper.updateById(article);
                return new resultVo(200,"已取消收藏",null);
//            }else {
//                tbCollect.setDelFlag(0);
//                tbCollect.setUpdateTime(new Date());
//                collectMapper.updateById(tbCollect);
//                article.setArticleCollectNums(article.getArticleCollectNums() + 1);
//                articleMapper.updateById(article);
//                return new resultVo(200,"收藏成功",null);
//            }
        }


    }

    public articleVo getCollectList(Integer pageNum, Integer pageSize) {
        List<resCollectList> list = collectMapper.getCollectList(pageNum,pageSize);
        int size = collectMapper.selectList(null).size();
        return new articleVo(true,200,"查询成功",list,size);
    }
}




